package com.xiao.dynamic_rule.service;

import com.xiao.dynamic_rule.pojo.LogBean;
import com.xiao.dynamic_rule.pojo.RuleParam;
import com.xiao.dynamic_rule.pojo.RuleParamAtomic;
import com.xiao.dynamic_rule.utils.ClickhouseCountQueryUtil;
import com.xiao.dynamic_rule.utils.ClickhouseUtil;
import org.apache.flink.api.common.state.ListState;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

public class UserActionCountQueryServiceClickHouseImpl implements UserActionCountQueryService {

    Connection conn;

    //在构造方法中创建ck连接
    public UserActionCountQueryServiceClickHouseImpl() throws SQLException, ClassNotFoundException {
        conn = ClickhouseUtil.getClickhouseConnection();

    }

    @Override
    public boolean queryActionCounts(String deviceId, ListState<LogBean> eventState, RuleParam ruleParam) throws Exception {
        List<RuleParamAtomic> userActionCountParams = ruleParam.getUserActionCountParams();

        for (RuleParamAtomic userActionCountParam : userActionCountParams) {

            //对当前原子条件拼接sql
            String sql = ClickhouseCountQueryUtil.getSql(deviceId, userActionCountParam);
            //获取一个ck的jdbc连接
            Statement statement = conn.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);

            // ResultSet是一个迭代器
            while (resultSet.next()) {
                int realCnt = resultSet.getInt(2);
                userActionCountParam.setRealCunts(realCnt);
            }

            //判断触发次数是否满足条件
            if (userActionCountParam.getRealCunts() < userActionCountParam.getCnts()) return false;

        }
        //如果程序走到这里说明触发次数满足条件中设置的次数
        return true;
    }

    @Override
    public boolean queryActionCount(String deviceId, ListState<LogBean> eventState, RuleParamAtomic atomicParam) throws Exception {
        return false;
    }
}
